import { getAccessToken, getTenantId } from '@/utils/auth'
import { genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile, UploadFile } from 'element-plus'
export function useUpload(uploadRef: Ref<UploadInstance | undefined>) {
  const { t } = useI18n() // 国际化
  const message = useMessage() // 消息弹窗

  const uploadHeaders = ref({
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId()
  })
  const UPLOAD_URL = import.meta.env.VITE_UPLOAD_URL

  const fileList = ref<UploadFile[]>([]) // 文件列表

  /** 上传成功 */
  const submitFormSuccess = (val) => {
    if (val.code != 200) {
      message.error('上传失败，请您重新上传！')
      return
    }
    console.log('val', val)
    console.log('fileList', fileList)
    // formData.value.filePath = val.data.url
  }

  /** 文件数超出替换为新文件 */
  const handleExceed: UploadProps['onExceed'] = (files) => {
    uploadRef.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    uploadRef.value!.handleStart(file)
  }
  /** 上传错误提示 */
  const submitFormError = (): void => {
    message.error('上传失败，请您重新上传！')
  }
  /** 上传进度 */
  const handleProgress = (evt) => {
    console.log('evt', evt)
  }
  /** 文件移除钩子 */
  const handleRemove = (file, files) => {
    console.log('file', file)
    console.log('files', files)
  }

  return {
    uploadHeaders,
    UPLOAD_URL,
    fileList,
    handleRemove,
    submitFormSuccess,
    handleExceed,
    submitFormError,
    handleProgress
  }
}
